from javax.swing import JLabel, JCheckBoxMenuItem,ButtonGroup,JRadioButtonMenuItem,JTextArea,JFrame, JMenu, JMenuBar,JToolBar, JMenuItem, JSpinner, SpinnerModel, SpinnerNumberModel, JComboBox, JTextField, JButton, JFileChooser, JScrollPane, ScrollPaneConstants, JList, JOptionPane
from javax.swing.event import ChangeListener, ChangeEvent
from java.awt.event import ActionEvent, ActionListener, ItemEvent
from java.awt import FlowLayout, BorderLayout
from model import *

class nanogoogleFrame:
    
    def __init__(self,model):
        self.myModel = model
        self.searchbar = JToolBar()
        self.button = JButton()
        self.chooserparams = [JFileChooser.FILES_ONLY, JFileChooser.DIRECTORIES_ONLY]
        self.searchfields = []
        self.dispButtonDic = {}
        self.sortButtonDic = {}
        self.indexops = {'Add File to Index':self.addFile, 'Add Folder to Index':self.addFolder, 'Add Webpage to Index':self.addWebPage, 'Remove File From Index':self.removeFile, 'Open Index':self.openIndex, 'Save Index':self.saveIndex, 'Clear Index':self.clearIndex}
        self.searchops = {'Additional Search': self.addSearch, 'Save Search Results': self.saveResults}
        self.spinners = []
        self.makeFrame()
        self.populateFrame()
        self.frame.show()
        
    def makeParameterBar(self):
        parameterBar=JToolBar()
        for param in self.myModel.mySearcher.parameters:
            spinner = JSpinner(SpinnerNumberModel(self.myModel.mySearcher.parameters[param],0,50,1))
            self.spinners.append(spinner)
            parameterBar.add(JLabel(param))
            parameterBar.add(spinner)
        parameterBar.setFloatable(False)
        return parameterBar             
                    
    def populateFrame(self):
        self.frame.setJMenuBar(self.makeMenuBar())
        self.frame.add(self.makeSearchBar(),BorderLayout.NORTH)
        self.frame.add(self.makeScrollPane(),BorderLayout.CENTER)
        self.frame.add(self.makeParameterBar(),BorderLayout.SOUTH)
    
    def makeFrame(self):
        self.frame = JFrame("Nanogoogle by TPK Microsystems")
        self.frame.setSize(800,450)
        self.frame.setLocationRelativeTo(None)
        self.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
       
    def makeMenuBar(self):
        menubar = JMenuBar()
        menubar.add(self.makeFileMenu())
        menubar.add(self.makeOptionsMenu())
        return menubar
        
    def makeSearchBar(self):
        self.searchbar.add(self.makeSearchButton())
        self.addSearch(e = None)
        self.searchbar.setFloatable(False)
        return self.searchbar
    
    def makeScrollPane(self):
        self.resultfield = JTextArea('Search Result Display')
        self.resultfield.setEditable(False)
        v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
        h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
        return JScrollPane(self.resultfield, v, h);
    
    def makeSearchButton(self):
        self.searchbutton = JButton('Search', actionPerformed = self.search)
        return self.searchbutton
    
    def makeSearchField(self):
        searchfield = JTextField('Enter Query Here')
        self.searchfields.append(searchfield)
        return searchfield

    def search(self, e):
        queries = self.retrieveQueries()
        parameters = self.checkParamSpinners()
        dispDic = self.checkDisplayButtons()
        sortmethod = self.checkRadioButtons()
        self.myModel.query(queries, parameters, dispDic, sortmethod, self.reversed.state)
    
    def checkRadioButtons(self):
        for item in self.sortButtonDic.keys():
            if (self.searchtype.isSelected(item.getModel())):
                return self.sortButtonDic[item]
    
    def checkParamSpinners(self):
        parameters = []
        for spin in self.spinners:
            parameters.append(spin.getValue())
        return parameters
    
    def checkDisplayButtons(self):
        dispDic = {}
        for label in self.dispButtonDic.keys():
            dispDic[label] = self.dispButtonDic[label].state
        return dispDic
    
    def retrieveQueries(self):
        queries = []
        for searchterm in self.searchfields:
            term = searchterm.text
            if (not term == 'Enter Query Here' and not term == ''):
                queries.append(term)
        return queries
                
    def makeFileMenu(self):
        file = JMenu("File")
        self.addMenuItems(self.indexops, file)
        file.addSeparator()
        self.addMenuItems(self.searchops, file)
        return file
    
    def addMenuItems(self, dic, menu):
        for string in dic.keys():
            menu.add(JMenuItem(string,actionPerformed = dic[string]))
    
    def makeOptionsMenu(self):
        option=JMenu("Options")
        self.addSortRadioButtons(option)
        option.addSeparator()
        self.addDisplayCheckBox(option)
        option.addSeparator()
        self.reversed=JCheckBoxMenuItem("Reverse Order")
        option.add(self.reversed)
        return option
    
    def addSortRadioButtons(self,option):
        self.searchtype=ButtonGroup()
        for sort in self.myModel.mySearcher.sortMethods:
            item = JRadioButtonMenuItem(sort)
            if (self.myModel.mySearcher.sortMethods[sort] == self.myModel.mySearcher.sortMethod):
                item.getModel().setSelected(True)
            self.sortButtonDic[item] = sort
            self.searchtype.add(item)
            option.add(item)
    
    def addDisplayCheckBox(self, option):
        for label in self.myModel.mySearcher.printOptions:
            item = JCheckBoxMenuItem(label)
            item.state = True
            self.dispButtonDic[label] = item
            option.add(item)
        
    def openParameters(self):
        self.makeParameterFrame()
        
    def addSearch(self, e): 
        self.searchbar.remove(self.searchbutton)
        self.searchbar.add(self.makeSearchField())
        self.searchbar.add(self.searchbutton)
    
    def fileChooser(self, text, parameter, function):
        chooser = JFileChooser()
        chooser.setDialogTitle(text)
        chooser.setFileSelectionMode(parameter)
        returnVal = chooser.showDialog(None, text)
        if (returnVal == JFileChooser.APPROVE_OPTION):
                selection = chooser.getSelectedFile()
                selectedPath = selection.getAbsolutePath()
                function(selectedPath)
    
    def addFolder(self, e):
        self.fileChooser('Index Folder', self.chooserparams[1], self.myModel.addFolder)
            
    def addFile(self, e):
        self.fileChooser('Index File', self.chooserparams[0], self.myModel.addFile)
    
    def addWebPage(self, e):
        location = JOptionPane.showInputDialog(None, 'Enter Web Address', 'Add Web Address', JOptionPane.QUESTION_MESSAGE, None, None, 'Web Address')
        self.myModel.addFile(location)
    
    def openIndex(self, e):
        self.fileChooser('Open Index', self.chooserparams[0], self.myModel.openIndex)
        
    def clearIndex(self, e):
        self.myModel.clearIndex()
    
    def saveIndex(self, e):
        self.fileChooser('Save Index', self.chooserparams[0], self.myModel.saveIndex)
    
    def saveResults(self, e):
        self.fileChooser('Save Results', self.chooserparams[0], self.myModel.saveResults) 
    
    def removeFile(self, e):
        docnames = self.myModel.getDocs()
        initselection = docnames[0]
        selection = JOptionPane.showInputDialog(None, 'Select File to Remove from Index',
        'Remove File', JOptionPane.QUESTION_MESSAGE, None, docnames, initselection)
        self.myModel.remove(selection)
        
    def display(self,text):
        self.resultfield.append("\n"+"\n"+text)
        
    def dialog(self, text):
        JOptionPane.showMessageDialog(self.frame, text)
        